
<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px"><zs-fl-selector @chooseZsfl="handleZsfl"></zs-fl-selector></el-aside>
      <el-container>
        <el-header>
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item>
              <el-input v-model="queryData.keyWord" placeholder="关键词" @keyup.enter="getDataList()"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"  @click="getDataList()">
                查询
              </el-button>
              <el-button type="default" @click="resetData()">清空</el-button>
            </el-form-item>
          </el-form>
        </el-header>
        <el-main><el-table :data="tableData" ref="multipleTableRef" border stripe style="width: 100%"
            highlight-current-row>
            <el-table-column type="selection" width="55" />
            <el-table-column label="序号" width="70" align="center">
              <template #default="{ $index }">
                {{ (pageIndex - 1) * pageSize + $index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="知识库标题" width="180" align="center">
              <template #default="scope">
                <el-popover effect="light" trigger="hover" placement="top" width="auto">
                  <template #default>
                    <div>问题类型: {{ scope.row.wtlx }}</div>
                    <div>问题场景: {{ scope.row.wtcj }}</div>
                  </template>
                  <template #reference>
                    {{ scope.row.zsbt }}
                  </template>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="wtnr" label="问题内容" width="220" align="center"/>
            <el-table-column prop="hdnr" label="回答内容" width="220" align="center"/>
            <el-table-column prop="fbsj" label="提交审核时间" width="160" align="center"/>
            <el-table-column fixed="right" label="操作" width="300" align="center">
              <template #default="scope">
                <el-button size="small" v-permission="'knowledge.detail'" @click="$router.push({ name: '知识详情', params: { id: scope.row.id } })">
                    知识详情
                </el-button>
                <el-button round type="info" size="small" @click="faileDetail(scope.row.id)">
                  审核不通过详情
                </el-button>
                <el-button round type="warning" size="small" @click="edit(scope.row.id)" v-permission="'knowledge.update'">
                  重新编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
            :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="total"
            layout="total, sizes, prev, pager, next, jumper" />
        </el-main>

        <!-- 查看知识审核不通过详情信息 -->
        <el-dialog v-model="dialogVisible" title="知识审核不通过详情信息">
          <el-descriptions title="不通过详情信息" :column="1" border>
            <el-descriptions-item label="知识标题" label-align="right" align="center" label-class-name="my-label"
              class-name="my-content">kooriookami</el-descriptions-item>
              <el-descriptions-item label="知识创建时间" label-align="right" align="center">
              {{ detailData.gmtCreate }}
            </el-descriptions-item>
            <el-descriptions-item label="审核员" label-align="right" align="center">
              <el-tag size="small">{{ detailData.examinerName }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="退回原因" label-align="right" align="center">
              {{ detailData.notPassedReason }}
            </el-descriptions-item>
            <el-descriptions-item label="退回时间" label-align="right" align="center">
              {{ detailData.gmtModified }}
            </el-descriptions-item>
          </el-descriptions>
        </el-dialog>

         <!-- 修改重新发起审核对话框 -->
         <el-dialog v-model="dialogFormVisible" title="修改重新审核知识">
            <el-form :model="form" label-width="120px" ref="ruleFormRef" :rules="rules">
              <el-form-item label="知识标题:" prop="zsbt">
                <el-input v-model="form.zsbt" />
              </el-form-item>
              <el-form-item label="知识分类:" prop="zslxIds">
                <div class="m-4">
                  <el-cascader v-model="form.zslxIds" :options="options" :props="props" />
                </div>
              </el-form-item>
              <el-form-item label="问题内容:" prop="wtnr">
                <el-input v-model="form.wtnr" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" />
              </el-form-item>
              <el-form-item label="问题同义句">
                <el-tag v-for="tag in wttyjTags" :key="tag" class="mx-1" closable :disable-transitions="false"
                  @close="handleClose(tag, true)">
                  {{ tag }}
                </el-tag>

                <el-input v-if="wtInputVisible" ref="wtInputRef" v-model="wtInputValue" class="ml-1 w-20" size="small"
                  @keyup.enter="handleInputConfirm(true)" @blur="handleInputConfirm(true)" />
                <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(true)">
                  + 添加问题同义句
                </el-button>
              </el-form-item>
              <el-form-item label="回答内容:" prop="hdnr">
                <el-input v-model="form.hdnr" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" />
              </el-form-item>
              <el-form-item label="回答同义句:">
                <el-tag v-for="tag in hdtyjTags" type="success" :key="tag" class="mx-1" closable
                  :disable-transitions="false" @close="handleClose(tag, false)">
                  {{ tag }}
                </el-tag>
                <el-input v-if="hdInputVisible" ref="hdInputRef" v-model="hdInputValue" class="ml-1 w-20" size="small"
                  @keyup.enter="handleInputConfirm(false)" @blur="handleInputConfirm(false)" />
                <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(false)">
                  + 添加回答同义句
                </el-button>
              </el-form-item>
              <el-form-item label="附件:">
                <!-- TODO 设置token再上传，否则无权限 -->
                <!-- 只能上传一个附件 -->
                <el-upload v-model:file-list="fileList" class="upload-demo" action="http://localhost:9000/file/upload"
                  :limit="1" :on-preview="handlePreview" :on-remove="handleRemove" :on-exceed="handleExceed"
                  :on-success="handleSuccess">
                  <el-button type="primary">Click to upload</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      目前只支持上传png、jpg格式文件(点击文件即可预览)
                    </div>
                  </template>
                </el-upload>

              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">Cancel</el-button>
                <el-button type="primary" @click="reExamine(ruleFormRef)">
                  Confirm
                </el-button>
              </span>
            </template>
          </el-dialog>


          <!-- 文件预览 -->
          <el-dialog v-model="preViewVisible" :width="'80%'">
            <preview :fileSuffix="fileSuffix" :imageSrc="imageSrc"></preview>
          </el-dialog>

       
      </el-container>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref ,nextTick} from 'vue'
import {
  getMyListApi, notPassDetailApi,getZsByIdApi,updateAndReExmineZsApi
} from '@/api/knowledgeBase/knowledge.js'
import { deleleFileApi } from "@/api/oss";
import { getTreeApi } from '@/api/knowledgeBase/typeTree.js'
import {
  ElInput,
  ElMessage,
  ElTable,
  FormInstance,
  FormRules,
} from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'

import ZsFlSelector from '@/views/common/ZsFlSelector.vue'
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const pageIndex = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const queryData = reactive({
  keyWord: '',
  zsfl: undefined
})
const dialogVisible = ref(false)
const detailData = ref({})
const dialogFormVisible = ref(false)
const form = ref({
  id: '',
  zsflmc: '',
  zsbt: '',
  zslxIds: [],
  fbzid: '',
  fbz: '',
  wtnr: '',
  wttyj: '',
  hdnr: '',
  hdtyj: '',
  fj: '',
})
const options = ref([])
// 分类属性映射
const props = {
  value: 'id',
  label: 'flmc',
  children: 'children',
}
const wttyjTags = ref([]) // 问题同义句
const hdtyjTags = ref([]) // 回答同义句
const wtInputVisible = ref(false)
const hdInputVisible = ref(false)
const wtInputValue = ref('')
const hdInputValue = ref('')
// 附件列表  
const fileList = ref<UploadUserFile[]>([])
const ruleFormRef = ref<FormInstance>()
const preViewVisible = ref(false)
const fileSuffix = ref("")// 文件类型
const imageSrc = ref('')
const wtInputRef = ref<InstanceType<typeof ElInput>>()
const hdInputRef = ref<InstanceType<typeof ElInput>>()


// 表单校验
const rules = reactive<FormRules>({
  zsbt: [{ required: true, message: '知识标题不能为空', trigger: 'blur' }],
  zslxIds: [{ required: true, message: '知识分类不能为空', trigger: 'blur' }],
  wtnr: [{ required: true, message: '问题内容不能为空', trigger: 'blur' }],
  hdnr: [{ required: true, message: '回答内容不能为空', trigger: 'blur' }],
})

// 点击分类
const handleZsfl = (zsflId: number) => {
  queryData.zsfl = zsflId

  console.log("知识分类为" + zsflId)
  // 触发查询
  getDataList()
}

// 点击查看不通过详情
const faileDetail = (id: number) => {
  dialogVisible.value = true

  // 获取不通过详情
  notPassDetailApi(id).then(res => {
    // 回显信息
    detailData.value = res.data
  })

}

// 修改每页数
const sizeChangeHandle = val => {
  pageSize.value = val
  pageIndex.value = 1
  getDataList()
}
// 修改当前页
const currentChangeHandle = val => {
  pageIndex.value = val
  getDataList()
}

// 重置查询条件
const resetData = () => {
  queryData.keyWord = '' 
  queryData.zsfl = undefined
  getDataList()
}

// 获取表格数据
const getDataList = () => {
  getMyListApi({
    page: pageIndex.value,
    limit: pageSize.value,
    keyWord: queryData.keyWord,
    zsflId: queryData.zsfl,
    status: "3", // 写死为查询审核失败的
  }).then(res => {
    tableData.value = res.data.list
    total.value = res.data.totalCount
  })
}

const handleClose = (tag: string, isWt: boolean) => {
  if (isWt) {
    wttyjTags.value.splice(wttyjTags.value.indexOf(tag), 1)
  } else {
    hdtyjTags.value.splice(hdtyjTags.value.indexOf(tag), 1)
  }
}
const handleInputConfirm = (isWt: boolean) => {
  if (isWt) {
    if (wtInputValue.value) {
      wttyjTags.value.push(wtInputValue.value)
    }
    wtInputVisible.value = false
    wtInputValue.value = ''
  } else {
    if (hdInputValue.value) {
      hdtyjTags.value.push(hdInputValue.value)
    }
    hdInputVisible.value = false
    hdInputValue.value = ''
  }
}
const showInput = (isWt: boolean) => {
  if (isWt) {
    wtInputVisible.value = true
    nextTick(() => {
      wtInputRef.value!.input!.focus()
    })
  } else {
    hdInputVisible.value = true
    nextTick(() => {
      hdInputRef.value!.input!.focus()
    })
  }
}

// 移除文件
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  console.log(file.url + "移除文件=================")
  deleleFileApi({ url: file.url })
}

// 预览
const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log("预览文件")
  preViewVisible.value = true
  console.log(uploadFile.url + "==========================")
  imageSrc.value = uploadFile.url
}

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 1, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
    } totally`
  )
}

// 附件上传成功
const handleSuccess = (response, uploadFile, uploadFiles) => {
  // 设置文件地址
  console.log('后端返回的图片地址为' + response.data)

  // 拼接文件url  = http://ip:port/file/response.data  response.data
  uploadFile.url = response.data.url
  fileSuffix.value = (response.data.url == null || response.data.url == "") ? "" : response.data.url.split('.').pop()
}

// 修改或添加
const reExamine = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      dialogFormVisible.value = false

     
        console.log('这是修改操作：' + JSON.stringify(form))
        updateAndReExmineZsApi({
          id: form.value.id,
          zsbt: form.value.zsbt,
          zslxIds: form.value.zslxIds,
          wtnr: form.value.wtnr,
          wttyj: wttyjTags.value.join('|'),
          hdnr: form.value.hdnr,
          hdtyj: hdtyjTags.value.join('|'),
          fj: fileList.value.length == 0 ? null : fileList.value[0].url, // 只能上传一个附件
        }).then(res => {
          // 关闭对话框
          dialogFormVisible.value = false
          // 提示成功
          ElMessage({
            type: 'success',
            message: '成功重新发起审核！！！！',
          })

          // 刷新列表
          getDataList()

        }) 
      }
     else {
      return false
    }
  })
}

// 清空表单
const clearForm = () => {
  ; (form.value.id = null),
    (form.value.zsflmc = ''),
    (form.value.zsbt = ''),
    (form.value.zslxIds = []),
    (form.value.wtnr = ''),
    (form.value.wttyj = ''),
    (form.value.hdnr = ''),
    (form.value.hdtyj = ''),
    (form.value.fj = ''),
    (wttyjTags.value = []),
    (hdtyjTags.value = [])
}
// 点击重新修改
const edit = async id => {
  // 清空表单
  clearForm()
  // 获取所有分类
  const res = await getTreeApi()
  options.value = res.data
  // 根据id获取数据
  getZsByIdApi(id).then(res => {
    form.value = res.data
    form.value.id = id
    // 问题同义句
    if (res.data.wttyj != null || res.data.wttyj != '') {

      var temp = res.data.wttyj.split('|')
      if (temp != null && temp.length > 0 && temp[0] != '') {
        wttyjTags.value = temp
      } else {
        wttyjTags.value = []
      }

    }
    // 回答同义句
    if (res.data.hdtyj != null || res.data.hdtyj != '') {

      var temp = res.data.hdtyj.split('|')
      if (temp != null && temp.length > 0 && temp[0] != '') {
        hdtyjTags.value = temp
      } else {
        hdtyjTags.value = []
      }
    }

    // 清空fileList数组  
    fileList.value = [];
    if (res.data.fj != null && res.data.fj != "") {
      // 设置文件RUL
      fileList.value.push({ name: "附件", url: res.data.fj })
      // 设置文件类型
      fileSuffix.value = (res.data.fj == null || res.data.fj == "") ? "" : res.data.fj.split('.').pop()
    }

    dialogFormVisible.value = true
  })
}
defineExpose({
  getDataList
});

getDataList()
</script>

<style scoped>
:deep(.my-label) {
  background: var(--el-color-success-light-9) !important;
}
:deep(.my-content) {
  background: var(--el-color-danger-light-9);
}
</style>